package babo.cd.physicalexperiment;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Map;

import babo.cd.physicalexperiment.app.MyApplication;
import babo.cd.physicalexperiment.utils.Out;
import babo.cd.physicalexperiment.view.TopBar;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import static android.content.ContentValues.TAG;


/**
 * Created by wy250 on 2017/9/26.
 */

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener ,TopBar.ITopBarClickListener{
    public FragmentManager manager;
    public Fragment currentFragment;
    public TopBar mTopBar;
    public Context context;
    public Handler hd;
    public SharedPreferences sharedPreferences;
    public Gson gson;

    @Subscribe(threadMode = ThreadMode.MAIN)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(bindView());

        EventBus.getDefault().register(this);
        initView();

        manager = getSupportFragmentManager();

//        getSupportActionBar().hide();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.blue));
        }
       context=this;
        hd=new Handler();
        gson=new Gson();
        sharedPreferences=getSharedPreferences("babowlsy",MODE_PRIVATE);
        MyApplication.getInstance().addActivity(this);
        initTopBar();

        setListener();
        loadData();

    }


    @Override
    public void leftClick() {
        finish();
    }
    @Override
    public void rightClick() {

    }
    public void goToNextActivity(Class activity) {
        Intent intent = new Intent(this, activity);
       startActivity(intent);
    }

    public void goToNextActivity(Class activity,Bundle bundle) {
        Intent intent = new Intent(this, activity);
        intent.putExtra("bundle",bundle);
        startActivity(intent);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.gc();
        try {
            EventBus.getDefault().unregister(this);
        }catch (Exception ex){}
    }

    private  void initTopBar(){
        try {
            mTopBar = getView(R.id.topbar);
            mTopBar.setTopBarClickListener(this);
        } catch (Exception e) {
            // TODO: handle exception
        }

    }
    public void setRightClickText(String str) {
        if (mTopBar != null) {
            mTopBar.setRightText(str);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setListener(){
    }
    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

//    @Override
//    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
//        super.onCreate(savedInstanceState, persistentState);
//        MyApplication.getInstance().addActivity(this);
//        initView();
//        loadData();
//    }

    @SuppressWarnings("unchecked")
    public final <E extends View> E getViewWithClick(int id) {
        try {

            ((E) findViewById(id)).setOnClickListener(this);

            return (E) findViewById(id);
        } catch (ClassCastException ex) {
            Out.out("没找到控件");
            throw ex;
        }
    }

    @SuppressWarnings("unchecked")
    public final <E extends View> E getView(int id) {
        try {

            return (E) findViewById(id);
        } catch (ClassCastException ex) {
            Out.out("没找到控件");
            throw ex;
        }
    }

    public void JumpAct(Context ct, Class<?> cls) {

        Intent i = new Intent(ct, cls);
        startActivity(i);
    }

    public void JumpActWithNoData(Class<?> cls) {

        Intent i = new Intent(getApplicationContext(), cls);
        startActivity(i);
    }

    public void JumpActAsResult(Context ct, Class<?> cls, int code) {

        Intent i = new Intent(ct, cls);
        i.putExtra("requescode", code);

        startActivityForResult(i, code);
    }

    public SharedPreferences getMyShareperance() {
        SharedPreferences sp = getSharedPreferences(MyApplication.LOGIN_INFO,
                MODE_PRIVATE);
        return sp;
    }

    protected abstract void initView();
    protected abstract View bindView();
    protected abstract void loadData();

    @Override
    public void onClick(View v) {
    }
    /**
     * fragment切换
     *
     * @param from
     *            当前fragment
     * @param to
     *            目标fragment
     * @param content
     *            fragment容器id
     */
    public void switchContent(Fragment from, Fragment to, int content) {
        if (currentFragment != to) {
            currentFragment = to;
            // 先判断是否被add过
            if (!to.isAdded()) {
                // 隐藏当前的fragment，add下一个到Activity中
                // manager.beginTransaction().hide(from).addToBackStack(null)
                // .add(content, to).commit();
                manager.beginTransaction().hide(from).add(content, to)
                        .commitAllowingStateLoss();
            } else {
                // 隐藏当前的fragment，显示下一个
                // manager.beginTransaction().hide(from).addToBackStack(null)
                // .show(to).commit();
                manager.beginTransaction().hide(from).show(to)
                        .commitAllowingStateLoss();
            }
        }
    }
    public  void hideInput(Context context, View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public  boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }
    /**
     * 实现点击空白处，软键盘消失事件
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View view = getCurrentFocus();
            Out.hideKeyboard(ev, view, BaseActivity.this);//调用方法判断是否需要隐藏键盘
        }
        return super.dispatchTouchEvent(ev);
    }
    public static void post3(String address, okhttp3.Callback callback, Map<String, String> map, File mfile, File mfile2, File mfile3, String token) {


        OkHttpClient client = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }


        if (mfile != null) {


            if (mfile2 == null) {
                String TYPE = "application/octet-stream";
                RequestBody fileBody = RequestBody.create(MediaType.parse(TYPE), mfile);
                RequestBody requestBody = builder
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("pic1", mfile.getName(), fileBody)
                        .build();
                Request request = new Request.Builder()
                        .url(address)
                        .post(requestBody)
                        .addHeader("Authorization", "Token " + token)
                        .build();
                client.newCall(request).enqueue(callback);
                Out.out("开始网络请求没111=="+address);
            } else {
                if (mfile3 == null) {
                    String TYPE = "application/octet-stream";
                    RequestBody fileBody = RequestBody.create(MediaType.parse(TYPE), mfile);
                    RequestBody fileBody2 = RequestBody.create(MediaType.parse(TYPE), mfile2);
                    RequestBody requestBody = builder
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("pic1", mfile.getName(), fileBody)
                            .addFormDataPart("pic2", mfile2.getName(), fileBody2)
                            .build();
                    Request request = new Request.Builder()
                            .url(address)
                            .post(requestBody)
                            .addHeader("Authorization", "Token " + token)
                            .build();
                    client.newCall(request).enqueue(callback);
                    Out.out("开始网络请求没222=="+address);

                } else {
                    String TYPE = "application/octet-stream";
                    RequestBody fileBody = RequestBody.create(MediaType.parse(TYPE), mfile);
                    RequestBody fileBody2 = RequestBody.create(MediaType.parse(TYPE), mfile2);
                    RequestBody fileBody3 = RequestBody.create(MediaType.parse(TYPE), mfile3);
                    RequestBody requestBody = builder
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("pic1", mfile.getName(), fileBody)
                            .addFormDataPart("pic2", mfile2.getName(), fileBody2)
                            .addFormDataPart("pic3", mfile3.getName(), fileBody3)
                            .build();
                    Request request = new Request.Builder()
                            .url(address)
                            .post(requestBody)
                            .addHeader("Authorization", "Token " + token)
                            .build();
                    client.newCall(request).enqueue(callback);
                    Out.out("开始网络请求没333=="+address);
                }

            }


        } else {
            Log.d(TAG, "post3: 文件不存在");
            RequestBody requestBody = builder
                    .setType(MultipartBody.FORM)
                    .build();
            Request request = new Request.Builder()
                    .url(address)
                    .post(requestBody)
                    .addHeader("Authorization", "Token " + token)
                    .build();
            client.newCall(request).enqueue(callback);
            Out.out("开始网络请求没：000---"+address);
        }

    }

}
